package com.example.loganalysis.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;

@RestController
public class IpfsDownloadController {

    @Value("${ipfs.download.url}")
    private String ipfsDownloadUrl; // 从配置文件读取 IPFS 基础下载 URL

    //下载普通日志文件
    @GetMapping("/downloadlog")
    public ResponseEntity<?> downloadFile(@RequestParam("ipfs_hash") String ipfsHash) {
        try {
            // 拼接完整的 IPFS URL
            String fullUrl = ipfsDownloadUrl + ipfsHash;
            URL url = new URL(fullUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("Failed to download file: HTTP " + responseCode);
            }

            // 获取文件流并读取内容
            InputStream inputStream = connection.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
            StringBuilder jsonContent = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                jsonContent.append(line);
            }

            // 使用 ObjectMapper 格式化 JSON 数据
            ObjectMapper objectMapper = new ObjectMapper();
            Object json = objectMapper.readValue(jsonContent.toString(), Object.class);
            String formattedJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json);

            // 转换为字节数组
            byte[] fileBytes = formattedJson.getBytes(StandardCharsets.UTF_8);

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + ipfsHash + ".txt");
            headers.add(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error downloading file: " + e.getMessage());
        }
    }
    //下载终端会话视频tar
    @GetMapping("/downloadlogTar")
    public ResponseEntity<?> downloadFileAsTar(@RequestParam("ipfs_hash") String ipfsHash) {
        try {
            // 拼接完整的 IPFS URL
            String fullUrl = ipfsDownloadUrl + ipfsHash;
            URL url = new URL(fullUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            // 检查响应码
            int responseCode = connection.getResponseCode();
            if (responseCode != HttpURLConnection.HTTP_OK) {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST)
                        .body("Failed to download file: HTTP " + responseCode);
            }

            // 读取文件内容
            InputStream inputStream = connection.getInputStream();
            byte[] fileBytes = inputStream.readAllBytes();

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + ipfsHash + ".tar");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/x-tar");

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(fileBytes);

        } catch (Exception e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("Error downloading file: " + e.getMessage());
        }
    }



}
